<?php
if (!isset($_SESSION)) {
    session_start();
}

class home extends CI_Controller {

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     * 		http://example.com/index.php/welcome
     * 	- or -  
     * 		http://example.com/index.php/welcome/index
     * 	- or -
     * Since this controller is set as the default controller in 
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see http://codeigniter.com/user_guide/general/urls.html
     */
    protected $configs;

    function __construct() {
        parent::__construct();
        $this->load->helper('url');
        $this->load->library('smarty3', '', 'smarty');
        $this->load->model('APanel/oauth_model');
        include APPPATH . 'libraries/defu.php';
        $this->oauth_model=new oauth_model();
        $this->tables=array(
                "940cc81cec5c7e119162e62bd57710f0"=>"adp_oauth"
        );
    }
    
    public function index() {
        require_once APPPATH . 'libraries/google-api-php-client0.6/src/Google_Client.php';
        require_once APPPATH . 'libraries/google-api-php-client0.6/src/contrib/Google_Oauth2Service.php';
        $client = new Google_Client();
        $client->setApplicationName("Google UserInfo PHP Starter Application");
        // Visit https://code.google.com/apis/console?api=plus to generate your
        // oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.
        $client->setClientId('619740911766.apps.googleusercontent.com');
        $client->setClientSecret('3N7SWMBtcKdt2WtjsVYwixGT');
        $client->setRedirectUri(base_url('OAuth'));
        $client->setDeveloperKey('AIzaSyDJnQDtRXjtT9Eks4ArrlmxgWFVvogFX8w');
        $oauth2 = new Google_Oauth2Service($client);

        if (isset($_GET['code'])) {
            $client->authenticate($_GET['code']);
            $_SESSION['token'] = $client->getAccessToken();
            redirect(base_url("OAuth"));
            return;
        }

        if (isset($_SESSION['token'])) {
            $client->setAccessToken($_SESSION['token']);
        }

        if (isset($_REQUEST['logout'])) {
            unset($_SESSION['token']);
            $client->revokeToken();
        }
        $Data=null;
        if ($client->getAccessToken()) {
            $user = $oauth2->userinfo->get();

            // These fields are currently filtered through the PHP sanitize filters.
            // See http://www.php.net/manual/en/filter.filters.sanitize.php
            $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
            // The access token may have been updated lazily.
            $_SESSION['token'] = $client->getAccessToken();
            if(!isset($_SESSION['GAPI']['user'])){
                $Acc=$this->oauth_model->getByEmail($user["email"]);
                if(isset($Acc[0])){
                    $params=array(
                        "Email"         =>$user["email"],
                        "Name"          =>$user["name"],
                        "AuthorityName" =>"Guest",
                        "Picture"       =>isset($user["picture"])?$user["picture"]:base_url('syslib/sysimages/user2.png'),
                        "Note"          =>  print_r($user,true)
                    );
                    //$this->oauth_model->update($Acc[0]->ID,$params);
                }else{
                    $params=array(
                        "Email"     =>$user["email"],
                        "Password"  =>md5($user["email"]),
                        "Name"      =>$user["name"],
                        "AuthorityName" =>"Guest",
                        "Picture"   =>isset($user["picture"])?$user["picture"]:base_url('syslib/sysimages/user2.png'),
                        "Note"      =>  print_r($user,true)
                    );
                    $this->oauth_model->insert($params);
                    $Acc=$this->oauth_model->getByEmail($user["email"]);
                }
                $_SESSION['GAPI']['user']=$Acc[0];
            }
            $Data["user"]=$_SESSION['GAPI']['user'];
            redirect(base_url("backend"));
        } else {
            $Data["authUrl"] = $client->createAuthUrl();
            redirect($Data["authUrl"]);
        }
        $Data["Accs"]=$this->oauth_model->gets();
        $this->smarty
                    ->assign('_SESSION', $_SESSION)
                    ->assign('Data', $Data)
                    ->display("OAuth/01_google_api");
    }
    function login($token=""){
        if(!isset($this->tables[$token])){
            echo json_encode(array("code"=>-1,"msg"=>"Token is invalid!"));return;
        }
        $code=-1;
        $msg = "Bad request!";
        if(isset($_SESSION['GAPI']['user']) && isset($_POST["password"])){
            $user=$_SESSION['GAPI']['user'];
            $email=$user->Email;
            $password=$_POST["password"];
            $Acc=$this->oauth_model->checkLogin($email, $password);
            if(isset($Acc[0])){
                $_SESSION["ADP"]["USER"]= objectToArray($Acc[0]);
                $_SESSION['isLoggedIn'] = true;
                $_SESSION['user'] =$_SESSION["ADP"]["USER"]["Name"];
                
                $tmp=$_SESSION["ADP"]["USER"]["Authority"];
                $tmp=";$tmp;";
                $tmp=  preg_split("~;~", $tmp, -1, PREG_SPLIT_NO_EMPTY);
                if(count($tmp)>0){
                    $tmp=$this->oauth_model->getAuthoritys($tmp);
                    $_SESSION["ADP"]["USER"]["Au"]=$tmp;
                }
                $code=1;
                $msg = "Login successful.";
            }else{
                $code=-1;
                $msg = "Login fail.Please, check Username or Password";
            }
        }
        echo json_encode(array("code"=>$code,"msg"=>$msg));
    }
    function changepassword($token=""){
        if(!isset($this->tables[$token])){
            echo json_encode(array("code"=>-1,"msg"=>"Token is invalid!"));return;
        }
        if(!isset($_SESSION["ADP"]["USER"])){
            $code=-1;
            $msg = "Bad request!";
        }else{
            $id=$_SESSION["ADP"]["USER"]["ID"];
            $currentpass=$_POST["currentpass"];
            $newpass=$_POST["newpass"];
            if($this->oauth_model->changepassword($id, $currentpass, $newpass)){
                $code=1;
                $msg = "Your password have been changed!";
            }else{
                $code=-1;
                $msg = "Sorry. Can't change your password!";
            }
        }
        echo json_encode(array("code"=>$code,"msg"=>$msg));
    }
    function logout(){
        session_destroy();
        redirect(base_url("OAuth"));
    }
}
